#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
抽象工厂模式 (Abstract Factory Pattern) - Python实现详解

🎯 模式概述：
抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口，而无需指定它们具体的类。
Python的ABC（抽象基类）和Protocol让抽象工厂的实现更加灵活和类型安全。

📚 Java vs Python 对比：

Java实现：
public abstract class UIFactory {
    public abstract Button createButton();
    public abstract TextField createTextField();
    public abstract Window createWindow();
}

public class WindowsUIFactory extends UIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
    // ... 其他方法
}

Python的优势：
1. ABC提供更灵活的抽象定义
2. Protocol支持结构化子类型
3. 类型注解提供更好的类型安全
4. 装饰器可以简化工厂注册
5. 动态特性支持运行时工厂选择

💡 关键理解：
抽象工厂模式解决的是"产品族"的创建问题，确保创建的对象之间是兼容的。
Python的实现更注重实用性和类型安全。
"""

from abc import ABC, abstractmethod
from typing import Protocol, Dict, Type, Any, Optional, List
from enum import Enum
from dataclasses import dataclass
import platform
import sys


# ==================== 抽象产品接口 ====================
# 使用Protocol定义产品接口，比Java接口更灵活

class Button(Protocol):
    """
    按钮抽象接口 - 使用Protocol实现结构化子类型
    
    Java等价接口：
    public interface Button {
        void render();
        void onClick(ActionListener listener);
        void setEnabled(boolean enabled);
        String getStyle();
    }
    
    Python Protocol的优势：
    1. 结构化子类型，不需要显式继承
    2. 支持鸭子类型
    3. 更好的类型检查
    4. 可以包含默认实现
    """
    
    def render(self) -> None:
        """渲染按钮"""
        ...
    
    def on_click(self, callback: callable) -> None:
        """设置点击回调"""
        ...
    
    def set_enabled(self, enabled: bool) -> None:
        """设置启用状态"""
        ...
    
    def get_style(self) -> str:
        """获取样式信息"""
        ...


class TextField(Protocol):
    """
    文本框抽象接口
    
    Java等价接口：
    public interface TextField {
        void render();
        void setText(String text);
        String getText();
        void setPlaceholder(String placeholder);
    }
    """
    
    def render(self) -> None:
        """渲染文本框"""
        ...
    
    def set_text(self, text: str) -> None:
        """设置文本"""
        ...
    
    def get_text(self) -> str:
        """获取文本"""
        ...
    
    def set_placeholder(self, placeholder: str) -> None:
        """设置占位符"""
        ...


class Window(Protocol):
    """
    窗口抽象接口
    
    Java等价接口：
    public interface Window {
        void show();
        void hide();
        void setTitle(String title);
        void setSize(int width, int height);
    }
    """
    
    def show(self) -> None:
        """显示窗口"""
        ...
    
    def hide(self) -> None:
        """隐藏窗口"""
        ...
    
    def set_title(self, title: str) -> None:
        """设置标题"""
        ...
    
    def set_size(self, width: int, height: int) -> None:
        """设置大小"""
        ...


# ==================== Windows平台具体产品 ====================

class WindowsButton:
    """
    Windows风格按钮 - 具体产品实现
    
    Java等价类：
    public class WindowsButton implements Button {
        private boolean enabled = true;
        private ActionListener clickListener;
        
        @Override
        public void render() {
            System.out.println("Rendering Windows-style button");
        }
    }
    """
    
    def __init__(self, text: str = "Button"):
        self.text = text
        self.enabled = True
        self.click_callback: Optional[callable] = None
        print(f"🪟 创建Windows按钮: {text}")
    
    def render(self) -> None:
        """渲染Windows风格按钮"""
        status = "启用" if self.enabled else "禁用"
        print(f"🎨 渲染Windows按钮: [{self.text}] ({status})")
        print("   样式: 3D边框, 渐变背景, 系统字体")
    
    def on_click(self, callback: callable) -> None:
        """设置点击回调"""
        self.click_callback = callback
        print(f"🖱️ 设置Windows按钮点击事件: {self.text}")
    
    def set_enabled(self, enabled: bool) -> None:
        """设置启用状态"""
        self.enabled = enabled
        print(f"⚙️ Windows按钮状态: {self.text} -> {'启用' if enabled else '禁用'}")
    
    def get_style(self) -> str:
        """获取样式信息"""
        return "Windows风格: 3D效果, 蓝色主题"
    
    def click(self) -> None:
        """模拟点击"""
        if self.enabled and self.click_callback:
            print(f"👆 点击Windows按钮: {self.text}")
            self.click_callback()


class WindowsTextField:
    """
    Windows风格文本框
    
    Java等价类：
    public class WindowsTextField implements TextField {
        private String text = "";
        private String placeholder = "";
        
        @Override
        public void render() {
            System.out.println("Rendering Windows-style text field");
        }
    }
    """
    
    def __init__(self, placeholder: str = "请输入文本..."):
        self.text = ""
        self.placeholder = placeholder
        print(f"🪟 创建Windows文本框: {placeholder}")
    
    def render(self) -> None:
        """渲染Windows风格文本框"""
        display_text = self.text if self.text else f"[{self.placeholder}]"
        print(f"🎨 渲染Windows文本框: {display_text}")
        print("   样式: 白色背景, 黑色边框, 系统字体")
    
    def set_text(self, text: str) -> None:
        """设置文本"""
        self.text = text
        print(f"📝 Windows文本框设置文本: {text}")
    
    def get_text(self) -> str:
        """获取文本"""
        return self.text
    
    def set_placeholder(self, placeholder: str) -> None:
        """设置占位符"""
        self.placeholder = placeholder
        print(f"💭 Windows文本框设置占位符: {placeholder}")


class WindowsWindow:
    """
    Windows风格窗口
    
    Java等价类：
    public class WindowsWindow implements Window {
        private String title = "Window";
        private int width = 800;
        private int height = 600;
        private boolean visible = false;
    }
    """
    
    def __init__(self, title: str = "Windows窗口"):
        self.title = title
        self.width = 800
        self.height = 600
        self.visible = False
        print(f"🪟 创建Windows窗口: {title}")
    
    def show(self) -> None:
        """显示窗口"""
        self.visible = True
        print(f"👁️ 显示Windows窗口: {self.title} ({self.width}x{self.height})")
        print("   特性: 标题栏, 最小化/最大化按钮, 系统菜单")
    
    def hide(self) -> None:
        """隐藏窗口"""
        self.visible = False
        print(f"🙈 隐藏Windows窗口: {self.title}")
    
    def set_title(self, title: str) -> None:
        """设置标题"""
        self.title = title
        print(f"📋 Windows窗口设置标题: {title}")
    
    def set_size(self, width: int, height: int) -> None:
        """设置大小"""
        self.width = width
        self.height = height
        print(f"📏 Windows窗口设置大小: {width}x{height}")


# ==================== macOS平台具体产品 ====================

class MacOSButton:
    """
    macOS风格按钮 - 具体产品实现
    
    Java等价类：
    public class MacOSButton implements Button {
        // macOS特有的实现
    }
    """
    
    def __init__(self, text: str = "Button"):
        self.text = text
        self.enabled = True
        self.click_callback: Optional[callable] = None
        print(f"🍎 创建macOS按钮: {text}")
    
    def render(self) -> None:
        """渲染macOS风格按钮"""
        status = "启用" if self.enabled else "禁用"
        print(f"🎨 渲染macOS按钮: [{self.text}] ({status})")
        print("   样式: 圆角边框, 扁平设计, SF字体")
    
    def on_click(self, callback: callable) -> None:
        """设置点击回调"""
        self.click_callback = callback
        print(f"🖱️ 设置macOS按钮点击事件: {self.text}")
    
    def set_enabled(self, enabled: bool) -> None:
        """设置启用状态"""
        self.enabled = enabled
        print(f"⚙️ macOS按钮状态: {self.text} -> {'启用' if enabled else '禁用'}")
    
    def get_style(self) -> str:
        """获取样式信息"""
        return "macOS风格: 扁平设计, 蓝色强调色"
    
    def click(self) -> None:
        """模拟点击"""
        if self.enabled and self.click_callback:
            print(f"👆 点击macOS按钮: {self.text}")
            self.click_callback()


class MacOSTextField:
    """
    macOS风格文本框
    """
    
    def __init__(self, placeholder: str = "请输入文本..."):
        self.text = ""
        self.placeholder = placeholder
        print(f"🍎 创建macOS文本框: {placeholder}")
    
    def render(self) -> None:
        """渲染macOS风格文本框"""
        display_text = self.text if self.text else f"[{self.placeholder}]"
        print(f"🎨 渲染macOS文本框: {display_text}")
        print("   样式: 圆角边框, 浅灰背景, SF字体")
    
    def set_text(self, text: str) -> None:
        """设置文本"""
        self.text = text
        print(f"📝 macOS文本框设置文本: {text}")
    
    def get_text(self) -> str:
        """获取文本"""
        return self.text
    
    def set_placeholder(self, placeholder: str) -> None:
        """设置占位符"""
        self.placeholder = placeholder
        print(f"💭 macOS文本框设置占位符: {placeholder}")


class MacOSWindow:
    """
    macOS风格窗口
    """
    
    def __init__(self, title: str = "macOS窗口"):
        self.title = title
        self.width = 800
        self.height = 600
        self.visible = False
        print(f"🍎 创建macOS窗口: {title}")
    
    def show(self) -> None:
        """显示窗口"""
        self.visible = True
        print(f"👁️ 显示macOS窗口: {self.title} ({self.width}x{self.height})")
        print("   特性: 统一标题栏, 红绿黄按钮, 阴影效果")
    
    def hide(self) -> None:
        """隐藏窗口"""
        self.visible = False
        print(f"🙈 隐藏macOS窗口: {self.title}")
    
    def set_title(self, title: str) -> None:
        """设置标题"""
        self.title = title
        print(f"📋 macOS窗口设置标题: {title}")
    
    def set_size(self, width: int, height: int) -> None:
        """设置大小"""
        self.width = width
        self.height = height
        print(f"📏 macOS窗口设置大小: {width}x{height}")


# ==================== Linux平台具体产品 ====================

class LinuxButton:
    """
    Linux风格按钮（GTK风格）
    """
    
    def __init__(self, text: str = "Button"):
        self.text = text
        self.enabled = True
        self.click_callback: Optional[callable] = None
        print(f"🐧 创建Linux按钮: {text}")
    
    def render(self) -> None:
        """渲染Linux风格按钮"""
        status = "启用" if self.enabled else "禁用"
        print(f"🎨 渲染Linux按钮: [{self.text}] ({status})")
        print("   样式: GTK主题, 自定义图标, 开源字体")
    
    def on_click(self, callback: callable) -> None:
        """设置点击回调"""
        self.click_callback = callback
        print(f"🖱️ 设置Linux按钮点击事件: {self.text}")
    
    def set_enabled(self, enabled: bool) -> None:
        """设置启用状态"""
        self.enabled = enabled
        print(f"⚙️ Linux按钮状态: {self.text} -> {'启用' if enabled else '禁用'}")
    
    def get_style(self) -> str:
        """获取样式信息"""
        return "Linux风格: GTK主题, 可定制外观"
    
    def click(self) -> None:
        """模拟点击"""
        if self.enabled and self.click_callback:
            print(f"👆 点击Linux按钮: {self.text}")
            self.click_callback()


class LinuxTextField:
    """
    Linux风格文本框
    """
    
    def __init__(self, placeholder: str = "请输入文本..."):
        self.text = ""
        self.placeholder = placeholder
        print(f"🐧 创建Linux文本框: {placeholder}")
    
    def render(self) -> None:
        """渲染Linux风格文本框"""
        display_text = self.text if self.text else f"[{self.placeholder}]"
        print(f"🎨 渲染Linux文本框: {display_text}")
        print("   样式: GTK主题, 可配置边框, 开源字体")
    
    def set_text(self, text: str) -> None:
        """设置文本"""
        self.text = text
        print(f"📝 Linux文本框设置文本: {text}")
    
    def get_text(self) -> str:
        """获取文本"""
        return self.text
    
    def set_placeholder(self, placeholder: str) -> None:
        """设置占位符"""
        self.placeholder = placeholder
        print(f"💭 Linux文本框设置占位符: {placeholder}")


class LinuxWindow:
    """
    Linux风格窗口
    """
    
    def __init__(self, title: str = "Linux窗口"):
        self.title = title
        self.width = 800
        self.height = 600
        self.visible = False
        print(f"🐧 创建Linux窗口: {title}")
    
    def show(self) -> None:
        """显示窗口"""
        self.visible = True
        print(f"👁️ 显示Linux窗口: {self.title} ({self.width}x{self.height})")
        print("   特性: 可定制标题栏, 窗口管理器集成, 主题支持")
    
    def hide(self) -> None:
        """隐藏窗口"""
        self.visible = False
        print(f"🙈 隐藏Linux窗口: {self.title}")
    
    def set_title(self, title: str) -> None:
        """设置标题"""
        self.title = title
        print(f"📋 Linux窗口设置标题: {title}")
    
    def set_size(self, width: int, height: int) -> None:
        """设置大小"""
        self.width = width
        self.height = height
        print(f"📏 Linux窗口设置大小: {width}x{height}")


# ==================== 抽象工厂接口 ====================

class UIFactory(ABC):
    """
    UI抽象工厂 - 定义创建UI组件族的接口
    
    Java等价抽象类：
    public abstract class UIFactory {
        public abstract Button createButton(String text);
        public abstract TextField createTextField(String placeholder);
        public abstract Window createWindow(String title);
        
        // 可以包含一些通用方法
        public final String getFactoryInfo() {
            return "UI Factory for " + getPlatform();
        }
        
        protected abstract String getPlatform();
    }
    
    Python ABC的优势：
    1. 更灵活的抽象方法定义
    2. 支持类型注解
    3. 可以包含具体方法实现
    4. 更好的多重继承支持
    """
    
    @abstractmethod
    def create_button(self, text: str = "Button") -> Button:
        """创建按钮 - 抽象方法，子类必须实现"""
        pass
    
    @abstractmethod
    def create_text_field(self, placeholder: str = "请输入文本...") -> TextField:
        """创建文本框 - 抽象方法，子类必须实现"""
        pass
    
    @abstractmethod
    def create_window(self, title: str = "窗口") -> Window:
        """创建窗口 - 抽象方法，子类必须实现"""
        pass
    
    @abstractmethod
    def get_platform(self) -> str:
        """获取平台信息 - 抽象方法"""
        pass
    
    def get_factory_info(self) -> str:
        """
        获取工厂信息 - 具体方法，提供默认实现
        
        这是模板方法模式的应用，定义了算法骨架
        """
        return f"UI工厂 for {self.get_platform()}"
    
    def create_dialog(self, title: str, message: str) -> Dict[str, Any]:
        """
        创建对话框 - 组合方法，使用其他工厂方法
        
        这展示了抽象工厂如何组合多个产品创建复杂对象
        """
        print(f"\n🏗️ 创建{self.get_platform()}对话框: {title}")
        
        # 创建对话框组件
        window = self.create_window(title)
        ok_button = self.create_button("确定")
        cancel_button = self.create_button("取消")
        message_field = self.create_text_field("")
        
        # 设置组件属性
        window.set_size(400, 200)
        message_field.set_text(message)
        
        # 返回对话框组件集合
        return {
            'window': window,
            'ok_button': ok_button,
            'cancel_button': cancel_button,
            'message_field': message_field,
            'platform': self.get_platform()
        }


# ==================== 具体工厂实现 ====================

class WindowsUIFactory(UIFactory):
    """
    Windows UI工厂 - 具体工厂实现
    
    Java等价类：
    public class WindowsUIFactory extends UIFactory {
        @Override
        public Button createButton(String text) {
            return new WindowsButton(text);
        }
        
        @Override
        public TextField createTextField(String placeholder) {
            return new WindowsTextField(placeholder);
        }
        
        @Override
        public Window createWindow(String title) {
            return new WindowsWindow(title);
        }
        
        @Override
        protected String getPlatform() {
            return "Windows";
        }
    }
    """
    
    def create_button(self, text: str = "Button") -> Button:
        """创建Windows风格按钮"""
        return WindowsButton(text)
    
    def create_text_field(self, placeholder: str = "请输入文本...") -> TextField:
        """创建Windows风格文本框"""
        return WindowsTextField(placeholder)
    
    def create_window(self, title: str = "窗口") -> Window:
        """创建Windows风格窗口"""
        return WindowsWindow(title)
    
    def get_platform(self) -> str:
        """获取平台信息"""
        return "Windows"


class MacOSUIFactory(UIFactory):
    """
    macOS UI工厂 - 具体工厂实现
    """
    
    def create_button(self, text: str = "Button") -> Button:
        """创建macOS风格按钮"""
        return MacOSButton(text)
    
    def create_text_field(self, placeholder: str = "请输入文本...") -> TextField:
        """创建macOS风格文本框"""
        return MacOSTextField(placeholder)
    
    def create_window(self, title: str = "窗口") -> Window:
        """创建macOS风格窗口"""
        return MacOSWindow(title)
    
    def get_platform(self) -> str:
        """获取平台信息"""
        return "macOS"


class LinuxUIFactory(UIFactory):
    """
    Linux UI工厂 - 具体工厂实现
    """
    
    def create_button(self, text: str = "Button") -> Button:
        """创建Linux风格按钮"""
        return LinuxButton(text)
    
    def create_text_field(self, placeholder: str = "请输入文本...") -> TextField:
        """创建Linux风格文本框"""
        return LinuxTextField(placeholder)
    
    def create_window(self, title: str = "窗口") -> Window:
        """创建Linux风格窗口"""
        return LinuxWindow(title)
    
    def get_platform(self) -> str:
        """获取平台信息"""
        return "Linux"


# ==================== 工厂选择器 ====================
# Python特有的动态工厂选择机制

class PlatformType(Enum):
    """
    平台类型枚举
    
    Java等价枚举：
    public enum PlatformType {
        WINDOWS("windows"),
        MACOS("macos"),
        LINUX("linux");
    }
    """
    WINDOWS = "windows"
    MACOS = "macos"
    LINUX = "linux"


class UIFactoryProvider:
    """
    UI工厂提供者 - 工厂的工厂（Factory of Factories）
    
    Java等价类：
    public class UIFactoryProvider {
        private static final Map<PlatformType, Class<? extends UIFactory>> factories = new HashMap<>();
        
        static {
            factories.put(PlatformType.WINDOWS, WindowsUIFactory.class);
            factories.put(PlatformType.MACOS, MacOSUIFactory.class);
            factories.put(PlatformType.LINUX, LinuxUIFactory.class);
        }
        
        public static UIFactory getFactory(PlatformType platform) {
            Class<? extends UIFactory> factoryClass = factories.get(platform);
            try {
                return factoryClass.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    Python的优势：
    1. 不需要复杂的反射机制
    2. 字典映射更直观
    3. 支持动态注册
    4. 更好的类型安全
    """
    
    _factories: Dict[PlatformType, Type[UIFactory]] = {
        PlatformType.WINDOWS: WindowsUIFactory,
        PlatformType.MACOS: MacOSUIFactory,
        PlatformType.LINUX: LinuxUIFactory
    }
    
    @classmethod
    def get_factory(cls, platform: PlatformType) -> UIFactory:
        """
        根据平台类型获取对应的UI工厂
        
        Args:
            platform: 平台类型
        
        Returns:
            UIFactory: 对应平台的UI工厂实例
        """
        factory_class = cls._factories.get(platform)
        if not factory_class:
            raise ValueError(f"不支持的平台: {platform}")
        
        return factory_class()
    
    @classmethod
    def get_current_platform_factory(cls) -> UIFactory:
        """
        根据当前运行平台自动选择工厂
        
        这是Python特有的便利方法，Java需要额外的系统检测
        """
        current_platform = platform.system().lower()
        
        if current_platform == "windows":
            return cls.get_factory(PlatformType.WINDOWS)
        elif current_platform == "darwin":  # macOS
            return cls.get_factory(PlatformType.MACOS)
        elif current_platform == "linux":
            return cls.get_factory(PlatformType.LINUX)
        else:
            print(f"⚠️ 未知平台: {current_platform}，使用Linux工厂")
            return cls.get_factory(PlatformType.LINUX)
    
    @classmethod
    def register_factory(cls, platform: PlatformType, factory_class: Type[UIFactory]) -> None:
        """
        注册新的工厂类型
        
        这展示了Python动态特性的优势
        """
        cls._factories[platform] = factory_class
        print(f"📝 注册UI工厂: {platform.value} -> {factory_class.__name__}")
    
    @classmethod
    def list_supported_platforms(cls) -> List[str]:
        """列出支持的平台"""
        return [platform.value for platform in cls._factories.keys()]


# ==================== 应用程序类 ====================
# 展示如何使用抽象工厂

@dataclass
class ApplicationConfig:
    """
    应用程序配置 - 使用@dataclass简化配置类
    
    Java等价类：
    public class ApplicationConfig {
        private final String title;
        private final int width;
        private final int height;
        private final PlatformType platform;
        
        // 构造函数、getter等
    }
    
    Python @dataclass的优势：
    1. 自动生成构造函数和方法
    2. 类型注解支持
    3. 更简洁的代码
    """
    title: str = "抽象工厂演示应用"
    width: int = 800
    height: int = 600
    platform: Optional[PlatformType] = None
    auto_detect_platform: bool = True


class Application:
    """
    应用程序类 - 使用抽象工厂创建UI组件
    
    Java等价类：
    public class Application {
        private UIFactory uiFactory;
        private Window mainWindow;
        private Button[] buttons;
        private TextField[] textFields;
        
        public Application(UIFactory factory) {
            this.uiFactory = factory;
        }
        
        public void createUI() {
            // 创建UI组件
        }
    }
    """
    
    def __init__(self, config: ApplicationConfig):
        self.config = config
        self.ui_factory = self._select_factory()
        self.main_window: Optional[Window] = None
        self.components: Dict[str, Any] = {}
        
        print(f"🚀 初始化应用程序: {config.title}")
        print(f"📱 使用平台: {self.ui_factory.get_platform()}")
    
    def _select_factory(self) -> UIFactory:
        """
        选择合适的UI工厂
        
        这展示了策略模式和抽象工厂模式的结合
        """
        if self.config.auto_detect_platform:
            return UIFactoryProvider.get_current_platform_factory()
        elif self.config.platform:
            return UIFactoryProvider.get_factory(self.config.platform)
        else:
            # 默认使用当前平台
            return UIFactoryProvider.get_current_platform_factory()
    
    def create_ui(self) -> None:
        """
        创建用户界面
        
        这个方法展示了抽象工厂模式的核心用法：
        使用同一个工厂创建一系列相关的对象
        """
        print(f"\n🏗️ 创建{self.ui_factory.get_platform()}风格的用户界面")
        print("-" * 50)
        
        # 创建主窗口
        self.main_window = self.ui_factory.create_window(self.config.title)
        self.main_window.set_size(self.config.width, self.config.height)
        
        # 创建按钮组件
        self.components['save_button'] = self.ui_factory.create_button("保存")
        self.components['load_button'] = self.ui_factory.create_button("加载")
        self.components['exit_button'] = self.ui_factory.create_button("退出")
        
        # 创建文本框组件
        self.components['name_field'] = self.ui_factory.create_text_field("请输入姓名")
        self.components['email_field'] = self.ui_factory.create_text_field("请输入邮箱")
        self.components['message_field'] = self.ui_factory.create_text_field("请输入消息")
        
        print(f"✅ UI组件创建完成，共{len(self.components) + 1}个组件")
    
    def setup_event_handlers(self) -> None:
        """
        设置事件处理器
        
        展示如何为工厂创建的组件设置行为
        """
        print(f"\n⚙️ 设置{self.ui_factory.get_platform()}事件处理器")
        print("-" * 50)
        
        # 设置按钮点击事件
        self.components['save_button'].on_click(lambda: print("💾 执行保存操作"))
        self.components['load_button'].on_click(lambda: print("📂 执行加载操作"))
        self.components['exit_button'].on_click(lambda: print("🚪 执行退出操作"))
        
        print("✅ 事件处理器设置完成")
    
    def render_ui(self) -> None:
        """
        渲染用户界面
        
        展示所有组件的渲染效果
        """
        print(f"\n🎨 渲染{self.ui_factory.get_platform()}用户界面")
        print("-" * 50)
        
        # 渲染主窗口
        if self.main_window:
            self.main_window.show()
        
        # 渲染所有组件
        for name, component in self.components.items():
            print(f"\n📦 渲染组件: {name}")
            component.render()
        
        print("\n✅ 界面渲染完成")
    
    def run(self) -> None:
        """
        运行应用程序
        
        完整的应用程序生命周期
        """
        print(f"\n🎯 启动应用程序: {self.config.title}")
        print("=" * 60)
        
        try:
            # 创建UI
            self.create_ui()
            
            # 设置事件处理
            self.setup_event_handlers()
            
            # 渲染界面
            self.render_ui()
            
            # 模拟用户交互
            self.simulate_user_interaction()
            
        except Exception as e:
            print(f"❌ 应用程序运行错误: {e}")
        finally:
            print(f"\n🏁 应用程序结束")
    
    def simulate_user_interaction(self) -> None:
        """
        模拟用户交互
        
        展示组件的实际使用
        """
        print(f"\n👤 模拟{self.ui_factory.get_platform()}用户交互")
        print("-" * 50)
        
        # 模拟文本输入
        self.components['name_field'].set_text("张三")
        self.components['email_field'].set_text("zhangsan@example.com")
        self.components['message_field'].set_text("这是一条测试消息")
        
        # 模拟按钮点击
        if hasattr(self.components['save_button'], 'click'):
            self.components['save_button'].click()
        if hasattr(self.components['load_button'], 'click'):
            self.components['load_button'].click()
        
        print("✅ 用户交互模拟完成")


# ==================== 测试和演示 ====================

def demonstrate_abstract_factory():
    """
    演示抽象工厂模式
    
    🎯 学习重点：
    1. 理解抽象工厂如何创建产品族
    2. 对比Java实现的差异和优势
    3. 掌握Python的ABC和Protocol使用
    4. 理解工厂选择和配置驱动
    """
    print("\n" + "="*60)
    print("🏭 抽象工厂模式 (Abstract Factory Pattern) 演示")
    print("="*60)
    
    # 1. 基本抽象工厂使用
    print("\n1️⃣ 基本抽象工厂使用")
    print("-" * 40)
    
    # 创建不同平台的工厂
    windows_factory = WindowsUIFactory()
    macos_factory = MacOSUIFactory()
    linux_factory = LinuxUIFactory()
    
    print(f"Windows工厂信息: {windows_factory.get_factory_info()}")
    print(f"macOS工厂信息: {macos_factory.get_factory_info()}")
    print(f"Linux工厂信息: {linux_factory.get_factory_info()}")
    
    # 使用Windows工厂创建组件
    print("\n🪟 使用Windows工厂创建组件:")
    win_button = windows_factory.create_button("Windows按钮")
    win_textfield = windows_factory.create_text_field("Windows输入框")
    win_window = windows_factory.create_window("Windows窗口")
    
    win_button.render()
    win_textfield.render()
    win_window.show()
    
    # 2. 工厂提供者使用
    print("\n2️⃣ 工厂提供者使用")
    print("-" * 40)
    
    print(f"支持的平台: {UIFactoryProvider.list_supported_platforms()}")
    print(f"当前平台: {platform.system()}")
    
    # 自动检测平台
    current_factory = UIFactoryProvider.get_current_platform_factory()
    print(f"自动选择的工厂: {current_factory.get_factory_info()}")
    
    # 手动指定平台
    macos_factory_2 = UIFactoryProvider.get_factory(PlatformType.MACOS)
    print(f"手动选择的macOS工厂: {macos_factory_2.get_factory_info()}")
    
    # 3. 对话框创建演示
    print("\n3️⃣ 对话框创建演示")
    print("-" * 40)
    
    # 创建不同平台的对话框
    platforms = [PlatformType.WINDOWS, PlatformType.MACOS, PlatformType.LINUX]
    
    for platform_type in platforms:
        factory = UIFactoryProvider.get_factory(platform_type)
        dialog = factory.create_dialog("确认对话框", "您确定要删除这个文件吗？")
        
        print(f"\n📱 {dialog['platform']}对话框组件:")
        print(f"  - 窗口: {dialog['window'].__class__.__name__}")
        print(f"  - 确定按钮: {dialog['ok_button'].__class__.__name__}")
        print(f"  - 取消按钮: {dialog['cancel_button'].__class__.__name__}")
        print(f"  - 消息框: {dialog['message_field'].__class__.__name__}")
    
    # 4. 完整应用程序演示
    print("\n4️⃣ 完整应用程序演示")
    print("-" * 40)
    
    # 创建应用程序配置
    config = ApplicationConfig(
        title="跨平台文本编辑器",
        width=1024,
        height=768,
        auto_detect_platform=True
    )
    
    # 创建并运行应用程序
    app = Application(config)
    app.run()
    
    # 5. 多平台对比演示
    print("\n5️⃣ 多平台对比演示")
    print("-" * 40)
    
    def create_and_compare_components():
        """创建并对比不同平台的相同组件"""
        platforms = [PlatformType.WINDOWS, PlatformType.MACOS, PlatformType.LINUX]
        
        for platform_type in platforms:
            factory = UIFactoryProvider.get_factory(platform_type)
            
            print(f"\n🎨 {platform_type.value.upper()}平台组件样式:")
            button = factory.create_button("测试按钮")
            print(f"  按钮样式: {button.get_style()}")
            
            textfield = factory.create_text_field("测试输入")
            window = factory.create_window("测试窗口")
            
            # 简单渲染
            button.render()
    
    create_and_compare_components()
    
    print("\n📊 抽象工厂模式总结")
    print("-" * 40)
    print("✅ 确保产品族的一致性")
    print("✅ 易于切换产品族")
    print("✅ 符合开闭原则")
    print("✅ Python的ABC和Protocol提供更好的类型安全")
    print("✅ 动态工厂选择比Java更灵活")


def demonstrate_advanced_features():
    """
    演示抽象工厂的高级特性
    """
    print("\n" + "="*60)
    print("🚀 抽象工厂模式高级特性演示")
    print("="*60)
    
    # 1. 工厂注册和扩展
    print("\n1️⃣ 工厂注册和扩展")
    print("-" * 30)
    
    # 创建自定义工厂
    class WebUIFactory(UIFactory):
        """Web UI工厂 - 扩展示例"""
        
        def create_button(self, text: str = "Button") -> Button:
            # 这里可以返回Web按钮实现
            print(f"🌐 创建Web按钮: {text}")
            return WindowsButton(text)  # 简化示例
        
        def create_text_field(self, placeholder: str = "请输入文本...") -> TextField:
            print(f"🌐 创建Web文本框: {placeholder}")
            return WindowsTextField(placeholder)  # 简化示例
        
        def create_window(self, title: str = "窗口") -> Window:
            print(f"🌐 创建Web窗口: {title}")
            return WindowsWindow(title)  # 简化示例
        
        def get_platform(self) -> str:
            return "Web"
    
    # 注册新的工厂类型
    web_platform = PlatformType("web")  # 动态创建枚举值
    UIFactoryProvider.register_factory(web_platform, WebUIFactory)
    
    # 使用新注册的工厂
    web_factory = UIFactoryProvider.get_factory(web_platform)
    web_button = web_factory.create_button("Web按钮")
    
    print(f"新平台支持: {UIFactoryProvider.list_supported_platforms()}")
    
    # 2. 工厂缓存和性能优化
    print("\n2️⃣ 工厂缓存和性能优化")
    print("-" * 30)
    
    class CachedUIFactoryProvider(UIFactoryProvider):
        """缓存工厂提供者 - 性能优化"""
        
        _factory_cache: Dict[PlatformType, UIFactory] = {}
        
        @classmethod
        def get_factory(cls, platform: PlatformType) -> UIFactory:
            """获取缓存的工厂实例"""
            if platform not in cls._factory_cache:
                cls._factory_cache[platform] = super().get_factory(platform)
                print(f"🗄️ 缓存工厂: {platform.value}")
            else:
                print(f"🎯 使用缓存工厂: {platform.value}")
            
            return cls._factory_cache[platform]
    
    # 测试缓存效果
    for _ in range(3):
        cached_factory = CachedUIFactoryProvider.get_factory(PlatformType.WINDOWS)
    
    print(f"缓存统计: {len(CachedUIFactoryProvider._factory_cache)}个工厂被缓存")


if __name__ == "__main__":
    # 运行演示
    demonstrate_abstract_factory()
    
    # 高级特性演示
    demonstrate_advanced_features()
    
    print("\n🎉 抽象工厂模式演示完成！")
    print("\n📚 学习要点回顾:")
    print("1. 抽象工厂确保产品族的一致性")
    print("2. Python的ABC和Protocol提供更好的抽象")
    print("3. 工厂提供者模式简化工厂选择")
    print("4. 动态注册支持运行时扩展")
    print("5. 缓存机制可以提高性能")